package com.agileai.bpm.domain.running;

import java.io.Serializable;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;

import com.agileai.util.StringUtil;
import com.agileai.util.XmlUtil;

public class WorkAttributes implements Serializable{
	private static final long serialVersionUID = 759744019094251523L;
	public static final String OPERA_DESC_KEY = "OPERA_DESC_KEY";
	private HashMap<String,String> attributes = new HashMap<String, String>();
	
	public void addAttribute(String key,String value){
		attributes.put(key,value);
	}
	
	public HashMap<String, String> getAttributes() {
		return attributes;
	}
	
	public String toXML(){
		String result = null;
		Document document = XmlUtil.createDocument();
		Element rootElement = document.addElement("row");
		Iterator<String> iter = attributes.keySet().iterator();
		while(iter.hasNext()){
			String key = iter.next();
			String value = attributes.get(key);
			rootElement.addElement(key).setText(value);
		}
		result = document.asXML();
		return result;
	}
	
	@SuppressWarnings("rawtypes")
	public void initFromXML(String xml){
		if (!StringUtil.isNullOrEmpty(xml)){
			Document document = XmlUtil.readDocument(new StringReader(xml));
	    	String rowPath = "//row";
	    	Node node = document.selectSingleNode(rowPath);
			Element rowElement = (Element)node;
			List eList = rowElement.elements();
			for (int i=0;i < eList.size();i++){
				Element field = (Element)eList.get(i);
				String key = field.getName();
				String value = field.getText();
				attributes.put(key,value);
			}
		}
	}
}
